package cloud.health.framework.nat.proxy;

import cloud.health.framework.computing.core.GlobalProperties;
import cloud.health.framework.nat.proxy.domain.Command;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class ProxyApplication {

    @Data
    public static class Common implements Serializable {
        private String ip;
        private Integer port;
    }

    @SneakyThrows
    public static void main(String[] args) {
        GlobalProperties.read();
        Common common = GlobalProperties.get("common", Common.class);
        List<Map<String, Object>> applications = GlobalProperties.array("applications", HashMap.class);
        Command cmd = null;
        for (; ; ) {
            try {
                if (Objects.nonNull(cmd)
                        && Objects.nonNull(cmd.getContext())
                        && !cmd.getContext().channel().isActive() ) {
                    cmd = null;
                }
                if (Objects.nonNull(cmd) && Objects.isNull(cmd.getContext())) {
                    cmd = null;
                }
                if (Objects.isNull(cmd)) {
                    if (Objects.nonNull(cmd)) {
                        cmd.stop();
                    }
                    cmd = Command.build(
                            common.getIp(),
                            common.getPort(),
                            applications
                    );
                    cmd.run();
                }
            } catch (Exception e) {
                log.error("cmd run error -->", e);
                continue;
            }
            Thread.sleep(3000L);
        }
    }
}

